<template>
  <div
    v-loading="loading"
    class="AddOrUpdate_main add_container role_container column_two"
  >
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态" style="margin-top:-5px;">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item />

        <el-form-item label="菜单权限" class="double">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-tree
            ref="menu"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
          >
            <span slot-scope="{ node, data }" class="tree-node">
              <span class="node_name">{{ data.label }}</span>
              <!--              <span v-if="data.menuType=='C'" class="node_operate">-->
              <span v-if="showDataPermission(data)" class="node_operate">
                <div class="name">数据权限:</div>
                <div class="value">
                  <el-select v-model="data.dataPermission">
                    <el-option
                      v-for="item in dataPermissionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </span>
            </span>
          </el-tree>
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { save, update, getById, treeselect as menuTreeselect, roleMenuTreeselect } from '@/api/system/role'
import fa from 'element-ui/src/locale/lang/fa'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isShow: {}
  },
  data() {
    return {
      formData: {
        roleId: undefined,
        roleName: undefined,
        remark: undefined,
        status: '1'
      },
      menuOptions: [],
      loading: false,
      menuExpand: false,
      menuNodeAll: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'change' }
        ]
      },
      dataPermissionOptions: [
        { value: '全部', label: '全部' },
        { value: '本部门', label: '本部门' },
        { value: '本人相关', label: '本人相关' }
      ],
      hideDataPermissionModule: ['设备报表', '生产报工'], // 在这里设置哪些模块或者页面不显示数据权限
      hideDataPermissionName: [] // 这里用来存放 通过 hideDataPermissionModule 字段匹配后的所有不展示数据权限的菜单（ 包括子集菜单 ）
    }
  },
  watch: {
    menuOptions(data) {
      const res = []
      const tag = false // 表示涉及到的自己是不是都不显示
      this.getHideDataPermissionName(res, data, tag)
      this.hideDataPermissionName = res
    }
  },
  created() {
    this.getMenuTreeselect()
  },
  methods: {
    getHideDataPermissionName(res, data, tag) { // 判断是否展示数据权限部分（ 获取不展示的菜单 ）
      const _this = this
      for (let i = 0; i < data.length; i++) {
        let forTag = tag
        if (tag) {
          res.push(data[i].label)
          forTag = true
        } else if (_this.hideDataPermissionModule.includes(data[i].label)) {
          res.push(data[i].label)
          forTag = true
        }
        if (data[i].children) {
          _this.getHideDataPermissionName(res, data[i].children, forTag)
        }
      }
    },
    showDataPermission(data) { // 判断是否展示数据权限部分
      if (data.menuType == 'C') {
        return !this.hideDataPermissionName.includes(data.label)
      } else {
        return false
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      if (this.id) {
        menuTreeselect(this.id).then(response => {
          this.menuOptions = response.data

          if (!this.id) { // 没有id就是新增
            Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
              this.formData[key] = this.defaultValue[key]
            })
            this.loading = false
          } else { // 有id就是编辑
            this.getById()
          }
        })
      } else {
        menuTreeselect('null').then(response => {
          this.menuOptions = response.data

          if (!this.id) { // 没有id就是新增
            Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
              this.formData[key] = this.defaultValue[key]
            })
            this.loading = false
          } else { // 有id就是编辑
            this.getById()
          }
        })
      }
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus
        return response
      })
    },
    getById() {
      const roleMenu = this.getRoleMenuTreeselect(this.id)
      getById(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        roleMenu.then(res => {
          const checkedKeys = res.checkedKeys
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false)
            })
          })
        }).finally(() => {
          this.loading = false
        })
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.data = this.$refs.menu.getCheckedNodes(false, true)
          if (!this.id) { // 没有id就是新增
            save(this.formData).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          } else { // 有id就是编辑
            update(this.formData).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        const treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
